
def train_keras_model(model, X_train, y_train, X_val, y_val, epochs=100, batch_size=128, patience=10):
    """
    训练Keras模型并添加早停机制

    参数:
    model: Keras模型实例
    X_train, y_train: 训练数据
    X_val, y_val: 验证数据
    epochs: 最大训练轮数
    batch_size: 批次大小
    patience: 早停等待轮数
    """
    import tensorflow as tf
    from tensorflow.keras.callbacks import EarlyStopping

    # 添加早停回调
    early_stopping = EarlyStopping(
        monitor='val_loss',
        patience=patience,
        restore_best_weights=True,
        verbose=1
    )

    # 训练模型
    history = model.fit(
        X_train, y_train,
        validation_data=(X_val, y_val),
        epochs=epochs,
        batch_size=batch_size,
        callbacks=[early_stopping],
        verbose=2  # 简洁输出
    )

    # 打印最终结果
    val_loss, val_acc = model.evaluate(X_val, y_val, verbose=0)
    print(f"\n训练结束 - 验证准确率: {val_acc:.4f}, 验证损失: {val_loss:.4f}")

    return history


def train_sklearn_model(model, X_train, y_train, X_val, y_val):
    model.fit(X_train, y_train)
    train_acc = model.score(X_train, y_train)
    val_acc = model.score(X_val, y_val)
    print(f"Training Accuracy: {train_acc:.4f}, Validation Accuracy: {val_acc:.4f}")
    print(" 训练完成")
    return None
